package com.subang.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.subang.common.core.domain.AjaxResult;
import com.subang.common.core.domain.entity.SysUser;
import com.subang.common.utils.DateUtils;
import com.subang.common.utils.SecurityUtils;
import com.subang.framework.web.service.SysLoginService;
import com.subang.framework.web.service.UserIntegralService;
import com.subang.system.service.ISysUserService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weChat")
public class WechatController {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.appsecret}")
    private String appsecret;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private UserIntegralService userIntegralService;



    @PostMapping("/decryptPhone")
    public AjaxResult decryptPhone(@RequestBody Map<String, String> requestData) {
        String code = requestData.get("code");
        String encryptedData = requestData.get("phone");
        String iv = requestData.get("iv");
        try {
            // 通过 code 获取 session_key 和 openid
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                    "&secret=" + appsecret +
                    "&js_code=" + code +
                    "&grant_type=authorization_code";
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(responseStr);
            if (jsonObject.containsKey("session_key")) {
                String sessionKey = jsonObject.getString("session_key");
                String openid = jsonObject.getString("openid");
                // 检查用户是否已存在
                SysUser existingUser = sysUserService.selectUserByOpenid(openid);
                if (existingUser == null) {
                    // 用户不存在，插入新记录
                    SysUser newUser = new SysUser();
                    newUser.setCreateTime(new Date());
                    newUser.setOpenid(openid);
                    // 用户名需要唯一，用来创建token
                    newUser.setUserName(openid);
                    newUser.setNickName("正备级");
                    newUser.setPassword(SecurityUtils.encryptPassword("123456")); // 示例密码，实际应加密处理
                    existingUser = newUser;
                    sysUserService.insertUser(existingUser);
                }
                // 调用解密函数
                //String phoneNumber = decryptData(encryptedData, sessionKey, iv);

                String token = loginService.loginWechat(existingUser.getUserName(), "123456");
                Date loginDate = existingUser.getLoginDate();
                if(null == loginDate){
                    userIntegralService.updateUserIntegral("firstLogin");
                }
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("user", existingUser);
                if(!DateUtils.isSameDay(loginDate, new Date())){
                    userIntegralService.updateUserIntegral("dailyLogin");
                }

                return AjaxResult.success("登录成功", result);
            } else {
                return AjaxResult.error("Failed to get session_key");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("An error occurred");
        }
    }

    private String decryptData(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);
            String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);

            // 解析JSON字符串并提取phoneNumber字段
            JSONObject jsonObject = JSONObject.parseObject(decryptedString);
            return jsonObject.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}